﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace PortableMediator
{
    public class MediatorAction : IWeakAction
    {
        private WeakReference _referenceObject;
        private MethodInfo _methodInfo;

        public MediatorAction(object target, MethodInfo methodInfo)
        {
            _referenceObject = new WeakReference(target, true);
            _methodInfo = methodInfo;
        }

        public async Task Invoke(object param)
        {
            await Task.Run(() =>
            {
                if (this.IsAlive())
                {
                    var target = this._referenceObject.Target;
                    _methodInfo.Invoke(target, new object[] { param });
                }
            });
        }

        public async Task Invoke(object param, object callback)
        {
            await this.Invoke(param);
        }

        public bool IsAlive()
        {
            return ((WeakReference)_referenceObject).IsAlive;
        }
    }
}
